// src/api/weatherApi.js
import request from './request';

const BASE_URL = 'https://restapi.amap.com/v3/weather/weatherInfo';
const API_KEY = 'b49db479db7ed5703052e4146f6744b9'; // 建议使用环境变量管理密钥

// 获取实时天气数据
export const getWeather = async (adcode) => {
  try {
    const response = await request({
      url: BASE_URL,
      method: 'get',
      params: {
        key: API_KEY,
        city: adcode,
        extensions: 'base',
      }
    });
    return {
      ...response.lives[0],
      temperature: response.lives[0].temperature.replace('℃', '') // 清理温度单位
    };
  } catch (error) {
    console.error('获取天气失败:', error);
    return null;
  }
};

export const getWeatherForecast = async (adcode) => {
  try {
    const response = await request({
      url: BASE_URL,
      method: 'get',
      params: {
        key: API_KEY,
        city: adcode, 
        extensions: 'all'
      }
    });
    return response.forecasts[0];
  } catch (error) {
    console.error('获取天气预报失败:', error);
    return null;
  }
};

// 新增城市搜索API函数（获取adcode和城市列表）
export const searchCity = async (keywords) => {
  try {
    const response = await request({
      url: 'https://restapi.amap.com/v3/config/district',
      method: 'get',
      params: {
        key: API_KEY,
        keywords: keywords,
        subdistrict: 0, // 不获取下级行政区
        extensions: 'base'
      }
    });
    return response.districts || [];
  } catch (error) {
    console.error('城市搜索失败:', error);
    return [];
  }
};